package com.vitas.coin.vm

import android.content.Intent
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.snap.alipay.ktx.payWithAli
import com.snap.base.ktx.enterBuy
import com.snap.base.ktx.isLogin
import com.snap.base.ktx.isVIP
import com.snap.base.ktx.payCompleted
import com.snap.base.ktx.requestUserInfo
import com.snap.common.main.BaseVM
import com.snap.base.util.BaseUtil
import com.snap.login.ktx.loginWithWX
import com.snap.util.toast
import com.snap.wx.ktx.payWithWX
import com.vitas.coin.ui.act.MainAct
import kotlinx.coroutines.launch

class BuyVM : BaseVM() {

    lateinit var back: () -> Unit
    lateinit var actionAct: () -> FragmentActivity

    // 0-未知；1-微信；2-支付宝
    val payWay = MutableLiveData<Int>().apply { value = 0 }

    fun clickPayWay(way: Int) {
        payWay.value = way
    }

    fun clickBuy(priceId: Int) {
        if (BaseUtil.isVIP()) {
            toast("当前用户是会员，无须重复支付")
            BaseUtil.payCompleted(true)
            gotoMainAct()
            return
        }
        if (!BaseUtil.isLogin()) {
            BaseUtil.loginWithWX(success = {
                clickBuy(priceId)
            }, failed = {
                toast("登录失败")
            })
            return
        }
        viewModelScope.launch {
            // 微信
            if (payWay.value == 1) {
                BaseUtil.payWithWX(priceId, success = {
                    paySuccess()
                }, failed = {
                    toast("支付失败")
                })
                return@launch
            }
            // 支付宝
            if (payWay.value == 2) {
                BaseUtil.payWithAli(actionAct.invoke(), priceId, success = {
                    paySuccess()
                }, failed = {
                    toast("支付失败")
                })
                return@launch
            }
            toast("请选择支付方式")
        }
    }
    private fun paySuccess() {
        toast("支付成功")
        BaseUtil.payCompleted(true)
        viewModelScope.launch {
            BaseUtil.requestUserInfo()
            gotoMainAct()
        }
    }
    private fun gotoMainAct() {
        val intent = Intent(actionAct.invoke(), MainAct::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        actionAct.invoke().startActivity(intent)
    }
}